package com.application.chiettinhdienluc.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.utils.Log;
import com.application.chiettinhdienluc.utils.Utils;
import com.sun.research.ws.wadl.Resource;

public class MySQLiteHelper extends SQLiteOpenHelper {

	public final static String TAG = MySQLiteHelper.class.getSimpleName();
	private SQLiteDatabase db;

	private volatile static MySQLiteHelper instance = null;
	private static final int DATABASE_VERSION = 1;
	public static final String DB_NAME = "chiettinh.sqlite";
	public static final String DB_ASSETS_NAME = "chiettinh.sqlite";
	
	private static final String TABLE_DB_VERSION = "db_version";
	
	public static final int NEW_VERSION = 0;
	
	//private Resource res = getResources();

	public synchronized static MySQLiteHelper getInstance() {
		
		
		
		if (instance == null) {
			try {
				synchronized (MySQLiteHelper.class) {
					if (instance == null) {
						instance = new MySQLiteHelper(MainApplication.getAppContext());
					}
				}
				
				instance.createDbVersionTable();
				
				Cursor cursor = instance.db.rawQuery("select version from " + TABLE_DB_VERSION, null);
				int oldVersion = 0;
				if (cursor.moveToFirst()) {
					oldVersion = cursor.getInt(cursor.getColumnIndex("version"));
				}
				if (cursor != null)
				{
					cursor.close();
					cursor = null;
				}
				
				if (NEW_VERSION > oldVersion) {
					// update database if needed
					instance.db.execSQL("update " + TABLE_DB_VERSION + " set version = " + NEW_VERSION + " where 1");
				}
			} catch (Exception e) {
				Log.e(TAG, e);
			}
		}

		return instance;
	}

	public MySQLiteHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		
		db = context.openOrCreateDatabase(DB_NAME, 0, null);
	}

	@Override
	public void onCreate(SQLiteDatabase database) {

	}
	
	public boolean isNotOpen() {
		return !db.isOpen();
	}

	@Override
	public void close() {
		synchronized (db) {
			if (db != null)
				db.close();
		}
		super.close();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}
	
	private void createDbVersionTable() {
		try {
			if (!isExistTable(TABLE_DB_VERSION)) {
				db.execSQL("create table " + TABLE_DB_VERSION + " (version INTEGER)");
				db.execSQL("insert into " + TABLE_DB_VERSION + " values (0)");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private static final String TABLE_CHECK_EXIST = "CREATE TABLE IF NOT EXISTS check_exist_database (option TEXT)";
	
	public void cloneDataBase()
	{
		try {
			if(db != null)
			{
				if(!isExistTable("check_exist_database"))
					copyDB();
				else
				{
					updateOrAddNewTable();
				}
			}
			
		} catch (Exception e) {
			throw new Error("Error copying database");
		}
	}

	public boolean isExistTable(String tableName) {
		boolean isExist = true;

		Cursor cursor = null;
		try {
			cursor = db.rawQuery("SELECT * FROM SQLITE_MASTER WHERE NAME = '" + tableName + "'", null);
			if (cursor != null && cursor.getCount() == 0) {
				isExist = false;
			}
		} catch (Exception e) {
			Log.e(TAG, e);
		} finally {
			if (cursor != null)
			{
				cursor.close();
				cursor = null;
			}
		}
		return isExist;
	}
	
	private void copyDB() {
		final String outFileName = GlobalData.DB_PATH + DB_NAME;

		InputStream myInput = null;		
		OutputStream myOutput = null;
		
		try {
			myInput = MainApplication.getAppContext().getAssets().open(DB_ASSETS_NAME);
			myOutput = new FileOutputStream(outFileName);

			// transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length;

			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}

			// Close the streams
			myOutput.flush();
			myOutput.close();
			myInput.close();

			db.execSQL(TABLE_CHECK_EXIST);
			//Utils.showMess(res.getString(R.string.tao_db_thanh_cong));
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
		}
	}

	public SQLiteDatabase getDb() {
		return db;
	}
	
	private void exportDB(final SQLiteDatabase db) {
		final String inFileName = GlobalData.DB_PATH + DB_NAME;
		final String outFileName = "/mnt/sdcard/chiettinh.sqlite";
	
//		File file = new File(outFileName);
//		if (file != null && !file.exists())
		{
			InputStream myInput = null;		//MainApplication.getAppContext().getAssets().open(DB_ASSETS_NAME);
			// Path to the just created empty db
			// Open the empty db as the output stream
			OutputStream myOutput = null;	//new FileOutputStream(outFileName);
			
			try {
				myInput = new FileInputStream(inFileName);
				myOutput = new FileOutputStream(outFileName);

				// transfer bytes from the inputfile to the outputfile
				byte[] buffer = new byte[1024];
				int length;

				while ((length = myInput.read(buffer)) > 0) {
					myOutput.write(buffer, 0, length);
				}

				// Close the streams
				myOutput.flush();
				myOutput.close();
				myInput.close();

				//db.execSQL(TABLE_CHECK_EXIST);
				//Utils.showMess(R.string.sao_luu_db_thanh_cong);
			} catch (Exception e) {
				Log.i("Export DB", e.toString());
				
			}
			finally{
				
			}
		}	
	}
	
	
	private void importDB(final SQLiteDatabase db) {
		final String outFileName = GlobalData.DB_PATH + DB_NAME;
		final String inFileName = "/mnt/sdcard/chiettinh.sqlite";
	
//		File file = new File(outFileName);
//		if (file != null && !file.exists())
		{
			InputStream myInput = null;		//MainApplication.getAppContext().getAssets().open(DB_ASSETS_NAME);
			// Path to the just created empty db
			// Open the empty db as the output stream
			OutputStream myOutput = null;	//new FileOutputStream(outFileName);
			
			try {
				myInput = new FileInputStream(inFileName);
				myOutput = new FileOutputStream(outFileName);

				// transfer bytes from the inputfile to the outputfile
				byte[] buffer = new byte[1024];
				int length;

				while ((length = myInput.read(buffer)) > 0) {
					myOutput.write(buffer, 0, length);
				}

				// Close the streams
				myOutput.flush();
				myOutput.close();
				myInput.close();

				//db.execSQL(TABLE_CHECK_EXIST);
				//Utils.showMess( R.string.phuc_hoi_db_thanh_cong);
				
				
			} catch (Exception e) {
				Log.i(TAG + ".ExportDb", e.toString());
				
			}
			finally{
				
			}
		}	
	}
	
	public void exportDataBase()
	{
		SQLiteDatabase db = this.getReadableDatabase();
		try {
			
			if(db != null && isExistTable("check_exist_database")) {
			   exportDB(db);
			}
			else
			{
				Log.i("MySQLiteHelper.exportDataBase", "file not found");				
			}
			
		} catch (Exception e) {
			throw new Error("Error exporting database");
		}
	}

	public void importDataBase()
	{
		SQLiteDatabase db = this.getReadableDatabase();
		try {
			
			if(db != null ) {
			   importDB(db);
			   createHinhAnhDetailsTable();
			}
			else
			{
				Log.i("MySQLiteHelper.importDataBase", "file not found");
				
			}
			
		} catch (Exception e) {
			throw new Error("Error importing database");
		}
	}

	
	public String getBackupDbFileDate() {
		
		  File f =new File("/mnt/sdcard/chiettinh.sqlite");
		  Date date;
		  if(f.exists()){
			  date = new Date(f.lastModified());
			  return new SimpleDateFormat("dd/MM/yyyy").format(date);
		  }
		  else {
			  return "";
		  }			  
	}
	
	private void updateOrAddNewTable()
	{
		try {
			createHinhAnhDetailsTable();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void createHinhAnhDetailsTable() {
		if (!isExistTable(HinhAnhChiTietDataSource.HINHANHCHITIET_DB_NAME)) {
			db.execSQL("create table " + HinhAnhChiTietDataSource.HINHANHCHITIET_DB_NAME + " (HSO_CHIETTINH_ID VARCHAR, File_Name VARCHAR, Ngay_Chup DATETIME, Submitted INTEGER DEFAULT (null))");			
		}
	}
	
	
} 